// AES.go
package componnet

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
)

var crypt_key = []byte("56e12d865e74114575978306")

func AesEncrypt(origStr string) (string, error) {
	origData := []byte(origStr)
	block, err := aes.NewCipher(crypt_key)
	if err != nil {
		return "", err
	}
	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, crypt_key[:blockSize])
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	// crypted := origData
	blockMode.CryptBlocks(crypted, origData)
	enData := base64.StdEncoding.EncodeToString(crypted)
	return enData, nil
}

func AesDecrypt(crypted string) (string, error) {
	enData, err := base64.StdEncoding.DecodeString(crypted)
	block, err := aes.NewCipher(crypt_key)
	if err != nil {
		return "", err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, crypt_key[:blockSize])
	origData := make([]byte, len(enData))
	// origData := crypted
	blockMode.CryptBlocks(origData, enData)
	origData = PKCS5UnPadding(origData)
	// origData = ZeroUnPadding(origData)
	origStr := string(origData)
	return origStr, nil
}

func ZeroPadding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{0}, padding)
	return append(ciphertext, padtext...)
}

func ZeroUnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
